<template>
  <div>
    <div class="tip" style="height: 597px;">
      <div style="height: 50px">
        <el-button type="primary" style="float: right" @click="dialogFormVisible = true">新增地址</el-button>
      </div>
      <el-dialog title="编辑" :visible.sync="dialogForm2Visible">
        <el-form :model="updateForm" ref="updateForm" :rules="editRules">
          <el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
            <el-input v-model="updateForm.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="电话" :label-width="formLabelWidth" prop="phone">
            <el-input v-model="updateForm.phone" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="地址" :label-width="formLabelWidth">
            <el-cascader
                v-model="areaCodes"
                :options="area"
                :props="{ expandTrigger: 'hover' }"
                ref="addArea"
                @change="handleChange">
            </el-cascader>
          </el-form-item>
          <el-form-item label="是否默认" :label-width="formLabelWidth">
            <el-radio-group v-model="updateForm.isDefault">
              <el-radio :label="1">默认地址</el-radio>
              <el-radio :label="0">非默认地址</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="详细地址" :label-width="formLabelWidth">
            <el-input v-model="detailAddress" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="delEdit">取 消</el-button>
          <el-button type="primary" @click="updateAddress">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog title="添加收货地址" :visible.sync="dialogFormVisible">
        <el-form :model="form" ref="form" :rules="addRule">
          <el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
            <el-input v-model="form.name" autocomplete="off" placeholder="请输入姓名"></el-input>
          </el-form-item>
          <el-form-item label="电话" :label-width="formLabelWidth" prop="phone">
            <el-input v-model="form.phone" autocomplete="off" placeholder="请输入电话"></el-input>
          </el-form-item>

          <el-form-item label="地址" :label-width="formLabelWidth">
            <el-cascader
                v-model="areaCodes"
                :options="area"
                :props="{ expandTrigger: 'hover' }"
                ref="addArea"
                @change="handleChange">
            </el-cascader>
          </el-form-item>
          <el-form-item label="是否默认" :label-width="formLabelWidth">
            <el-radio-group v-model="form.isDefault">
              <el-radio :label="1">默认地址</el-radio>
              <el-radio :label="0">非默认地址</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="详细地址" :label-width="formLabelWidth">
            <el-input v-model="detailAddress" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="addAddress">确 定</el-button>
        </div>
      </el-dialog>

      <el-table
          :data="tableData"
          border
          style="width: 1040px;">

        <el-table-column
            prop="name"
            label="姓名"
            fixed
            width="100">
        </el-table-column>
        <el-table-column
            prop="phone"
            label="电话"
            width="160">
        </el-table-column>
        <el-table-column
            prop="address"
            label="地址"
            width="400">
        </el-table-column>
        <el-table-column
            prop="createdTime"
            label="日期"
            width="200">
        </el-table-column>
        <el-table-column
            fixed="right"
            label="操作"
            width="150">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleClick(scope.row)">编辑</el-button>
            <!--            <el-button type="text" size="small">设为默认</el-button>-->
            <el-button type="text" size="small" @click="deleteAddress(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import area from '@/utils/area'
// import login from "@/router/pages/login";

export default {
  name: "GetAddress",
  data() {
    var validateName = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入昵称'))
      } else {
        const reg = /[^]*/
        if (value.length < 100 && reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入字符在15以内的昵称'))
        }
      }

    };
    var validatePhone = (rule, value, callback) => {
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(value)) {
        return callback()
      }
      // 返回一个错误提示
      callback(new Error('请输入合法的手机号码'))
    };
    var validateDetailAddress =  (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入详细地址'))
      } else {
        const reg = /[^]*/
        if (value.length < 200 && reg.test(value)) {
          callback()
        } else {
          return callback(new Error('字符过长！'))
        }
      }

    };
    return {
      userId: null,
      area,
      areaCodes: [],
      areaLabels: [],
      detailAddress: '',
      value: [],
      tableData: [],
      dialogForm2Visible: false,
      addressId: null,

      updateForm: {
        name: '',
        phone: '',
        address: '',
        areaCode: 0,
        userId: 0,
        isDefault: 1
      },
      dialogFormVisible: false,
      form: {
        name: '',
        phone: '',
        address: '',
        areaCode: 0,
        userId: 0,
        isDefault: 1
      },
      formLabelWidth: '120px',
      editRules: {
        name: [
          { validator: validateName, trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
        ],
        phone: [
          { validator: validatePhone, trigger: 'blur' },

        ],
        detailAddress: [
          { validator: validateDetailAddress, trigger: 'blur' }
        ],
        tempRow:null,
        tempSource:null
      },
      addRule:{
        name: [
          { validator: validateName, trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
        ],
        phone: [
          { validator: validatePhone, trigger: 'blur' },

        ],
      }
    }
  },

  created() {
    this.getRequest('/cms/user/getInfo').then(res => {
      this.userId = res.data.id
    }).then(() => {
      this.getList()
    })

  },
  methods: {
    delEdit(){
      // this.choicFrom = this.tempForm
      this.dialogForm2Visible = false
      this.$router.go(0)
    },
    getList() {
      this.getRequest('/cms/address/getList/' + this.userId).then((resp) => {
        console.log(resp)
        this.tableData = resp.data.sort((x, y) => y.isDefault - x.isDefault)
      })
    },
    handleChange(val) {
      this.areaLabels = this.$refs['addArea'].getCheckedNodes()[0].pathLabels
      this.areaCodes = val
    },
    deleteAddress(row) {
      this.addressId = row.id
      this.getRequest('/cms/address/del/' + this.addressId).then((resp) => {
        if (resp.status === 200) {
          this.$message.success('删除成功')
          location.reload()
        } else {
          this.$message.success('删除失败')
        }
      })
    },
    handleClick(row) {
      this.addressId = row.id
      this.dialogForm2Visible = true
      this.updateForm = row
      this.areaCodes = []
      const area = row.areaCode + ''
      for (let i = 0; i < 3; i++) {
        const s = area.substring(0, 2 + 2 * i);
        this.areaCodes.push(s)
      }
      this.areaCodes = Object.assign([], this.areaCodes);
      const splice = row.address.split(' ');
      delete splice[0]
      delete splice[1]
      delete splice[2]
      console.log(splice)
      this.areaLabels = this.getAreaLabel(this.areaCodes)
      this.detailAddress = splice.join('')
    },
    getAreaLabel(code) {
      const Label = []
      area.some(item => {
        if (item.value === code[0]) {
          Label.push(item.label)
          item.children.some(ii => {
            if (ii.value === code[1]) {
              Label.push(ii.label)
              ii.children.some(iii => {
                if (iii.value === code[2]) {
                  Label.push(iii.label)
                  return true;
                }
              })
              return true;
            }
          })
          return true;
        }
      })
      return Label
    },
    addAddress() {
      if (this.detailAddress === '') {
        this.$message.info("请输入详细地址")
        return;
      }
      this.form.userId = this.userId
      this.form.address = this.areaLabels.join(' ') + ' ' + this.detailAddress.trim()
      this.form.areaCode = this.areaCodes[this.areaCodes.length - 1]
      this.postRequest('/cms/address/add', this.form).then((resp) => {
        this.$message.success(resp.message);
        this.dialogFormVisible = false
        this.getList()
      })
    },
    updateAddress() {
      this.$refs.updateForm.validate(valid=>{
        if(valid){
          if (this.detailAddress === '') {
            this.$message.info("请输入详细地址")
            return;
          }
          this.updateForm.userId = this.userId
          this.updateForm.address = this.areaLabels.join(' ') + ' ' + this.detailAddress.trim()
          this.updateForm.areaCode = this.areaCodes[this.areaCodes.length - 1]
          this.postRequest('/cms/address/update/' + this.addressId, this.updateForm).then((resp) => {
            this.$message.success(resp.message);
            this.dialogForm2Visible = false
          }).then(() => {
            this.getList()
          })
        }else{
          this.$message.error('表单不合法！')
        }
      })

    }
  }
}
</script>

<style scoped>
.tip {
  width: 1021px;
  margin: 10px auto;
  overflow: hidden;
  position: relative;
  left: 14em;
  top: 2em;
}

</style>